package cn.jimmie.learn.sdk.async;

import android.os.AsyncTask;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import cn.jimmie.learn.pbc.base.BaseActivity;
import cn.jimmie.learn.pbc.resource.ISdk;
import cn.jimmie.learn.pbc.http.MockHttp;
import cn.jimmie.learn.pbc.resource.Plugin;
import cn.jimmie.learn.pbc.resource.PluginConst;
import cn.jimmie.learn.pbc.resource.ShareInstance;
import cn.jimmie.learn.sdk.SdkApi;
import cn.jimmie.learn.sdk.util.PluginUtils;

/**
 * function :
 *
 * <p> Create Time: 2019年02月14日 22:55 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public class LoadRemotePluginTask extends AsyncTask<Boolean, Integer, Boolean> {
    private WeakReference<BaseActivity> mHost;

    private OnRemotePluginListener mListener;

    public void setListener(OnRemotePluginListener listener) {
        this.mListener = listener;
    }

    public LoadRemotePluginTask(BaseActivity host) {
        mHost = new WeakReference<>(host);
    }

    @Override
    protected Boolean doInBackground(Boolean... bs) {
        BaseActivity activity = mHost.get();
        boolean useRemote = bs[0];
        boolean done = false;
        // 拉取服务端的插件进行更新
        if (useRemote) {
            // 此处使用同步请求, 易于操作
            done = MockHttp.pullRemotePlugin(activity);
            // 重新设置 classLoader
            Plugin plugin = (PluginUtils.loadPluginManager(activity,
                    PluginConst.PLUGIN_NAME));
            ShareInstance.instance().setPlugin(plugin);

            // 重新获取单例
            ISdk instance = PluginUtils.hookPluginInstance(
                    plugin.getPluginClassLoader());
            SdkApi.reloadSdk(instance);

            // 重新加载插件资源
            activity.loadPluginResourceTheme();
            plugin.setAskUpdate(false);
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return done;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        if (mListener != null) {
            mListener.onLoadRemotePluginFinished();
        }
    }


    public interface OnRemotePluginListener {
        void onLoadRemotePluginFinished();
    }
}
